<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>策略模式实现表单验证</title>
</head>

<body>
    <form action="/" id="myForm" method="POST">
        用户名：<input name='user' type="text"> 密 码 ：<input name='pwd' type="text">
        <!-- 手机号：<input name='phone' type="text"> -->
        <button type="submit" name='btn'>提交表单</button>
    </form>
</body>

</html>

<script>
    var form = document.getElementById('myForm');
    form.btn.onclick = function(e) {
        var userVal = form.user.value;
        var pwdVal = form.pwd.value;

        if (!userVal) {
            console.log('用户名不能为空');
            return false;
        }

        if (!pwdVal || (pwdVal.length <= 6)) {
            console.log('密码长度必须大于6位');
            return false;
        }

        console.log('提交成功');
        return false;
    }

    //策略对象
    var strategy = {
        require: function(val, msg) {
            if (!val) {
                return msg
            }
        },
        min: function(val, length, msg) {
            if (!val || (val.length <= 6)) {
                return msg
            }
        },
        phone: function(val, msg) {
            let patt = /^1[3-9]\d{9}$/
            let flag = patt.test(val)
            if (!flag) {
                return msg
            }
        }
    }

    //策略类
    var Validate = function() {
        this.rules = []

        this.add = function(dom, rule, msg) {
            let args = rule.split(':')
            let func = args.shift();
            args.push(msg)
            args.unshift(dom.value)

            let obj = {
                func,
                args
            }
            this.rules.push(obj)
                //strategy[func]
        }

        this.check = function() {
            var errors = []
            for (var i = 0; i < this.rules.length; i++) {
                var error = strategy[this.rules[i].func].apply(strategy, this.rules[i].args) //调用策略对象中的方法
                if (error) {
                    errors.push(error)
                }
            }
            return errors
        }
    }

    function checkForm() {
        var validate = new Validate()
        validate.add(form.user, 'require', '用户名必须填写')
        validate.add(form.pwd, 'min:6', '密码长度必须大于6位')
        validate.add(form.phone, 'phone', '请输入正确手机号')
        var res = validate.check()

        if (res.length) {
            console.log(res)
        } else {
            console.log('验证成功')
        }

        return false;
    }
    var form = document.getElementById('myForm')
    form.btn.onclick = checkForm
</script>